package com.iplant.base.utils.sys;

import lombok.extern.slf4j.Slf4j;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

@Slf4j
public class LocalUtils {
    public static List<String> GetNetworkInfo(List<String> wMacList) {
        List<String> wResult = new ArrayList<>();
        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            boolean wHas = false;
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = networkInterfaces.nextElement();
                Enumeration<InetAddress> inetAddress = networkInterface.getInetAddresses();
                if (networkInterface.isLoopback() || !networkInterface.isUp())
                    continue;
                byte[] macAddress = networkInterface.getHardwareAddress();
                if (macAddress == null)
                    continue;

                wHas = false;

                while (inetAddress.hasMoreElements()) {
                    InetAddress inetAddress1 = inetAddress.nextElement();
                    if (inetAddress1.isLoopbackAddress() || inetAddress1.getHostAddress().indexOf(':') >= 0)
                        continue;
                    wResult.add(inetAddress1.getHostAddress());
                    wHas = true;
                }
                if (!wHas)
                    continue;

                // 将字节转换为MAC地址格式的字符串
                StringBuilder macAddressBuilder = new StringBuilder();
                for (byte b : macAddress) {
                    macAddressBuilder.append(String.format("%02X:", b));
                }
                if (macAddressBuilder.length() > 0) {
                    // 移除字符串最后的冒号
                    macAddressBuilder.deleteCharAt(macAddressBuilder.length() - 1);
                }
                wMacList.add(macAddressBuilder.toString());
            }
        } catch (Exception e) {
            log.error("获取IP地址 Mac地址失败", e);
        }
        return wResult;
    }



    public static String getShortHostName() {
        try {
            InetAddress localHost = InetAddress.getLocalHost();
            String hostName = localHost.getHostName();
            // 分割主机名，只获取第一部分
            String[] parts = hostName.split("\\.");
            return parts[0];
        } catch (Exception e) {
            log.error("获取HostName失败", e);
            return "unknown_host";
        }
    }
}
